<template>
  <div>
    <upload-excel-index :on-success="handleSuccess" :before-upload="beforeUpload" style="margin-top: 70px" />
  </div>
</template>

<script>
import { arrayToFormData, transExcel } from '@/utils'
import { impEmployees } from '@/api/employees'
export default {
  name: 'UploadExcel',

  data() {
    return {
      res: []
    }
  },
  created() {},
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        // message: 'Please do not upload files larger than 1m in size.',
        message: '请不要上传大于1M的文件.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      // console.log(results, header)
      // 调用处理excel的函数
      const data = transExcel(results)
      // console.log(results)
      // 发请求
      this.hUploadExcel(data, event)
    },
    // 封装导入excel的函数
    async hUploadExcel(data, e) {
      // console.log(e.target)
      try {
        // if (!e.target.files[0]) return
        // // 获取 file 对象
        // const file = e.target.files[0]
        // console.log(arrayToFormData(data))
        const dat = arrayToFormData(data)
        // 发请求
        const res = await impEmployees(dat)
        // console.log(res)
        // 提示用户
        this.$message.success(res.message)
        // 后退一页
      } catch (e) {
        this.$message.error(e.message)
      }
    }
  }
}
</script>
